import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export interface ServoDTO {
  baud: number;
  servo_id: number;
  error_code: number;
}

export interface ServoDataStore {
  searchResults: Array<{ servo: ServoDTO }>;
  commandOutput: string[];
  isVisible: boolean;

  addSearchResult: (baud: number, servo_id: number, error_code: number) => void;
  addCommandOutput: (data: string) => void;
  clearMessages: () => void;
  clearCommandOutput: () => void;
  handleShow: () => void;
  handleHide: () => void;
  toggleVisibility: () => void;
  addDebugMessage: () => void;
}

export const useServoDataStore = create<ServoDataStore>()(
  persist(
    (set, get) => ({
      searchResults: [],
      commandOutput: [],
      isVisible: false,

      addSearchResult: (baud, servo_id, error_code) => {
        set((state) => ({
          searchResults: [
            ...state.searchResults,
            {
              servo: {
                baud: baud ?? 0,
                servo_id: servo_id ?? 0,
                error_code: error_code ?? 0,
              },
            },
          ],
        }));
      },

      addCommandOutput: (data) => {
        set((state) => ({
          commandOutput: [...state.commandOutput, data],
        }));
      },

      clearMessages: () => set({ searchResults: [] }),

      clearCommandOutput: () => set({ commandOutput: [] }),

      handleShow: () => set({ isVisible: true }),

      handleHide: () => set({ isVisible: false }),

      toggleVisibility: () => set((state) => ({ isVisible: !state.isVisible })),

      addDebugMessage: () => {
        get().addSearchResult(9600, 1, 0);
      },
    }),
    {
      name: 'servoDataStore',
      partialize: (state) => ({
        searchResults: state.searchResults,
      }),
    }
  )
);

// selector 用于获取 searchResultsWithServo
export const selectSearchResultsWithServo = (state: ServoDataStore) =>
  state.searchResults.map((item) => ({ servo: item.servo }));
